﻿//Tzi Yong

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;

namespace Tzync
{
    public partial class ProfileUIForm : Form
    {
        private String systemId, profileName;
        private Profile profile;   
        private String rootAddress; //path of root folder of profile
        private SyncTool syncTool; 
        private List<String> profileList = new List<String>();  //list of profiles
        private DialogResult dialogResult;    //result of dialog box

        public ProfileUIForm()
        {
            InitializeComponent();
        }

        private void ProfileUIForm_Load(object sender, EventArgs e)
        {
            systemId = Utility.GetCPUId();  //get CPU id of this computer
            try
            {
                syncTool = new SyncTool(systemId);  //initialize features
            }
            catch (DirectoryNotFoundException d)
            {
                if (d.Type == ActionType.Rollback)
                    infoLabel.Text = "Rollback folder could not be created.\n\nBut don't worry, Tzync will try again next time it starts.";
            }

            DisplayProfile();

            //tooltips  
            logoToolTip.SetToolTip(tzyncLogoPB, "Click here to visit Tzync's website!");
            newBtnToolTip.SetToolTip(createProfileBtn, "Click here to create a new profile");
            loadBtnToolTip.SetToolTip(loadProfileBtn, "Click here to load the selected profile");
            deleteBtnToolTip.SetToolTip(deleteProfileBtn, "Click here to Remove the selected profile");
            helpBtnToolTip.SetToolTip(helpBtn, "Click here to download our help file online!");
            aboutBtnToolTip.SetToolTip(aboutBtn, "Click here to learn more about Tzync and check for updates!");
            quitBtnToolTip.SetToolTip(quitBtn, "Why leave when you are having fun?");
            
            // check if there was any safe sync done
            if (!syncTool.SafelySynchronized())
            {
                syncTool.PerformSafeSync();
                MessageBox.Show("Tzync has detected that your last sync was not successful.\n\nDon't worry, your files have been recovered!\n\nPlease sync again.",
                    "Last sync unsuccessful!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

            try
            {
                //deletes rollback files of profiles deleted on other computers
                syncTool.CleanupRollback();
            }
            catch (IOException)
            {
                infoLabel.Text = "Rollback files could not be cleaned up.\n\nBut don't worry, Tzync will try again next time it starts.";
            }
        }

        private void ProfileUIForm_Shown(object sender, EventArgs e)
        {
            DisplayProfile();   //refresh list of profiles
        }

        private void tzyncLogoPB_Click(object sender, EventArgs e)
        {
            infoLabel.Text = "";
            Process.Start("http://code.google.com/p/tzync/");   //opens Tzync's website
        }

        private void CreateProfileBtn_Click(object sender, EventArgs e)
        {
            bool isCreated = false; //check whether profile has been created successfully
            infoLabel.Text = "";
            this.Visible = false;
            AddNewProfileUIForm newProfileUI = new AddNewProfileUIForm(syncTool, isCreated);
            newProfileUI.ShowDialog();
            isCreated = newProfileUI.IsCreated;
            this.Visible = true;

            if (isCreated)
                infoLabel.Text = "Profile has been created!";

            DisplayProfile();
        }

        private void LoadProfileBtn_Click(object sender, EventArgs e)
        {
            MatchProfileUIForm matchProfileUI;
            RenameProfileUIForm renameProfileUI;
            SyncUIForm syncUI;
            bool directoryExists;   //check if profile directory exists
            bool isCompleted = false;   //check if profile has been completed with two folders
            bool isDeleted = false; //check if profile has been deleted by user

            infoLabel.Text = "";

            if (profileLV.SelectedItems.Count > 0)  //if user selected a profile
            {
                profileName = profileLV.SelectedItems[0].Text;

                try
                {
                    syncTool.LoadProfile(profileName);  //retrieve profile Information 
                }
                catch (FileNotFoundException f)
                {
                    if (f.Type == ActionType.Rollback)
                        syncTool.RollbackSystemHandler.CreateRollback();
                }

                profile = syncTool.GetProfile();

                if (profile.SystemName == SystemType.Host)
                    rootAddress = profile.RootAddressHost;
                else
                    rootAddress = profile.RootAddressGuest;

                if (!profile.HasGuest && systemId != profile.CPUIdHost)   //if profile needs to be completed
                {
                    this.Visible = false;
                    matchProfileUI = new MatchProfileUIForm(syncTool, isCompleted);   //ask user to complete profile
                    matchProfileUI.ShowDialog();
                    isCompleted = matchProfileUI.IsCompleted;
                    this.Visible = true;

                    profile = syncTool.GetProfile();    //get updated profile
                    DisplayProfile();
                }
                
                directoryExists = CheckProfileFolder(); //check if profile folder for this computer exists

                if (!directoryExists)   //profile folder has been renamed, deleted, or moved
                {
                    isCompleted = false;
                    if (profile.SystemName != SystemType.Host && !profile.HasGuest) //do nothing if profile is not complete
                        return;

                    this.Visible = false;
                    renameProfileUI = new RenameProfileUIForm(syncTool, isCompleted); //ask user to locate folder or delete profile
                    renameProfileUI.ShowDialog();
                    isCompleted = renameProfileUI.IsCompleted;
                    isDeleted = renameProfileUI.IsDeleted;
                    this.Visible = true;
                    profile = syncTool.GetProfile();
                    DisplayProfile();
                   
                    directoryExists = CheckProfileFolder();
                    if (!directoryExists)   //If the user chose to delete the profile, do nothing
                    {
                        if (isDeleted)
                            infoLabel.Text = "Profile has been deleted!";

                        DisplayProfile();
                        return;
                    }
                }

                if (isCompleted || profile.HasHost)    //show main screen if profile is ok 
                {
                    this.Visible = false;
                    syncUI = new SyncUIForm(syncTool);
                    dialogResult = syncUI.ShowDialog();

                    if (dialogResult == DialogResult.OK)
                    {
                        this.Visible = true;
                        DisplayProfile();
                    }
                }
                else
                    return;
            }
            else
            {
                infoLabel.Text = "No profile was selected to load!";
                return;
            }
        }

        private void profileLV_DoubleClick(object sender, EventArgs e)
        {
            LoadProfileBtn_Click(sender, e);
        }

        private void deleteProfileBtn_Click(object sender, EventArgs e)
        {
            infoLabel.Text = "";
            if (profileLV.SelectedItems.Count > 0)
            {
                dialogResult = MessageBox.Show("Are you sure you want to delete the selected profile?",
                "Delete selected profile?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dialogResult == DialogResult.Yes)
                {
                    infoLabel.Text = "Deleting in progress...";
                    Cursor.Current = Cursors.WaitCursor;

                    try
                    {
                        syncTool.RemoveProfile(profileLV.SelectedItems[0].Text);  //Remove profile
                    }
                    catch (IOException)
                    {
                        infoLabel.Text = "Profile cannot be deleted.";
                        return;
                    }

                    profileLV.Items.Remove(profileLV.SelectedItems[0]);

                    infoLabel.Text = "Selected profile(s) have been removed!";
                    Cursor.Current = Cursors.Default;
                }
                else
                    return;
            }
            else
            {
                infoLabel.Text = "No profile was selected for removal!";
                return;
            }
        }

        private void quitBtn_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void helpBtn_Click(object sender, EventArgs e)
        {
            infoLabel.Text = "";
            Process.Start("http://tzync.googlecode.com/files/Tzync_User_Guide_V2.pdf");
        }

        private void aboutBtn_Click(object sender, EventArgs e)
        {
            infoLabel.Text = "";
            AboutUIForm aboutUI = new AboutUIForm();
            aboutUI.ShowDialog();
        }

        //displays list of profiles
        private void DisplayProfile()
        {
            profileLV.Items.Clear();
            Profile newProfile;
            profileList = syncTool.GetAvailableProfiles();
            foreach (String profileName in profileList)
            {
                newProfile = new Profile(systemId, profileName);
                ListViewItem profileLVI = new ListViewItem();
                profileLVI.Text = newProfile.ProfileName;
                profileLVI.SubItems.Add(newProfile.RootAddressHost);
                profileLVI.SubItems.Add(newProfile.RootAddressGuest);
                profileLV.Items.Add(profileLVI);

                Utility.ResizeColumns(profileLV);
            }
        }

        //checks if profile folder is missing
        private bool CheckProfileFolder()
        {
            if (profile.SystemName == SystemType.Host)
            {
                if (!Directory.Exists(profile.RootAddressHost))
                    return false;
                else
                    return true;
            }
            else
            {
                if (!Directory.Exists(profile.RootAddressGuest))
                    return false;
                else
                    return true;
            }
        }
    }
}
